package com.devops.admin.service.impl;

import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Set;

/**
 * @author jxt
 * @Notes
 * @date 2024/7/22 16:31
 */
@Service
@Slf4j
public class ApisixAdminApiServiceImpl {

    @Value(value = "${apisix.admin-api.host:https://gateway-api.uat.967111.net}")
    private String HOST;

    @Value(value = "${apisix.admin-api.token:edd1c9f034335f136f87ad84b625c8f1}")
    private String API_TOKEN;

    /**
     * 获取全局规则配置的黑名单
     * @return com.sun.tools.javac.util.List<java.lang.String>
     * @author jxt
     * @date 2024/7/22 16:48
     */
    public List<String> getBlockList() {
        String result = HttpRequest.get(HOST + "/apisix/admin/global_rules/1")
                .header("X-API-KEY", API_TOKEN)
                .execute()
                .body();
        log.debug("result: {}", result);
        JSONObject globalRules = JSONUtil.parseObj(result);
        List<String> blockList = globalRules.getByPath("value.plugins.ip-restriction.blacklist", List.class);
        return blockList;
    }

    public List<String> setBlockList(Set<String> ips) {
        String result = HttpRequest.patch(HOST + "/apisix/admin/global_rules/1/plugins/ip-restriction/blacklist")
                .header("X-API-KEY", API_TOKEN)
                .body(JSONUtil.toJsonStr(ips))
                .execute()
                .body();
        log.debug("result: {}", result);
        JSONObject globalRules = JSONUtil.parseObj(result);
        List<String> blockList = globalRules.getByPath("value.plugins.ip-restriction.blacklist", List.class);
        return blockList;
    }
}
